package com.xsj.service.impl;

import com.xsj.dto.ResponseDto;
import com.xsj.mapper.LoginMapper;
import com.xsj.pojo.User;
import com.xsj.service.LoginService;
import com.xsj.utils.Capt;
import com.xsj.utils.JwtUtils;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import com.xsj.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private Capt capt;
    @Autowired
    private LoginMapper loginMapper;
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    public LoginServiceImpl() {
    }

    public ResponseDto login(String account, String password, String inputCaptcha, String key) {
        boolean b = this.capt.verifyCaptcha(key, inputCaptcha);
        if (!b) {
            return ResponseDto.err(401, "验证码错误");
        } else {
            User login = this.loginMapper.login(account, password);
            if (login == null) {
                return ResponseDto.err(401, "用户名或密码错误");
            } else {
                String token = this.jwtUtils.generateToken(login.getUserName(), login.getUserId());
                this.redisTemplate.opsForValue().set(token, login, this.jwtUtils.getExpiration(), TimeUnit.SECONDS);
                HashMap<String, Object> result = new HashMap();
                result.put("token", token);
                result.put("user", login);
                return ResponseDto.success(result);
            }
        }
    }

    @Override
    public ResponseDto register(UserVO user) {
        boolean b = capt.verifyCaptcha(user.getKey(), user.getInputCaptcha());
        if (!b) {
            return ResponseDto.err(401, "验证码错误");
        }else {
            int register = loginMapper.register(user);
            if (register<=0){
                return ResponseDto.err(401, "注册失败");
            }else {
                return ResponseDto.success("注册成功");
            }
        }
    }
}
